package cn.zwx.member.svc.rpc;

import cn.zwx.base.entity.ResponseEntity;
import cn.zwx.base.exception.BizWrapException;
import cn.zwx.member.svc.domain.constans.MemberConstans;
import cn.zwx.member.svc.manager.DistributedManager;
import cn.zwx.member.svc.rpc.facade.DubboCaptchaService;
import cn.zwx.member.svc.rpc.vo.GenCaptchaVO;
import com.wf.captcha.ArithmeticCaptcha;
import org.apache.dubbo.apidocs.annotations.ApiDoc;
import org.apache.dubbo.apidocs.annotations.ApiModule;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangwenxue
 * ApiModule 必要 api-doc会查找所有带有@ApiModule的bean对象
 */
@Service
@ApiModule(value = "生成验证码相关接口", apiInterface = DubboCaptchaService.class)
@DubboService(version = "v1.0.0",interfaceClass = DubboCaptchaService.class,timeout = 8000)
public class DubboCaptchaServiceImpl implements DubboCaptchaService {

    @Resource
    private DistributedManager distributedManager;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    @ApiDoc(value = "生成验证码图片接口")
    public ResponseEntity<GenCaptchaVO> getCaptcha() throws BizWrapException {
        // 1.生成验证码
        ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha (110, 36);
        final String verCode = arithmeticCaptcha.text().toLowerCase();
        final String distributedId = distributedManager.getDistributedId();
        // 2.保存到redis
        String redisKey = MemberConstans.CAPTCHA_CACHE_KEY_PREFIX+distributedId;
        redisTemplate.opsForValue().set(redisKey,verCode, MemberConstans.INT_5, TimeUnit.MINUTES);
        // 3.返回参数
        final GenCaptchaVO genCaptchaVO = new GenCaptchaVO();
        genCaptchaVO.setCaptchaId(distributedId);
        genCaptchaVO.setSpecCaptcha(arithmeticCaptcha.toBase64());
        return ResponseEntity.success(genCaptchaVO);
    }
}
